import sqlite3
import random
import json
from pathlib import Path
from datetime import datetime
import argparse

# ---
from dict_api import DictionaryAPI
api = DictionaryAPI(timeout=15)

DB_NAME = "vocabulary.db"
STATE_FILE = "word_review_state.json"

class WordSampler:
    def __init__(self):
        self.conn = sqlite3.connect(DB_NAME)
        self.state_path = Path(STATE_FILE)
        self.state = self._load_state()

    def _load_state(self):
        """加载或初始化状态文件"""
        if self.state_path.exists():
            with open(self.state_path, 'r') as f:
                return json.load(f)
        else:
            return {
                "remaining": self._get_all_word_ids(),
                "reviewed": [],
                "last_review": None
            }

    def _save_state(self):
        """保存当前状态"""
        with open(self.state_path, 'w') as f:
            json.dump(self.state, f, indent=2)

    def _get_all_word_ids(self):
        """获取数据库所有单词ID"""
        cur = self.conn.execute("SELECT id FROM words")
        return [row[0] for row in cur.fetchall()]

    def _reset_state(self, force=False):
        """重置学习进度"""
        if not force and len(self.state["remaining"]) > 0:
            confirm = input(f"仍有 {len(self.state['remaining'])} 个未复习单词，确定要重置吗？(y/N): ")
            if confirm.lower() != 'y':
                return False

        self.state = {
            "remaining": self._get_all_word_ids(),
            "reviewed": [],
            "last_review": datetime.now().isoformat()
        }
        self._save_state()
        return True

    def get_daily_words(self, count):
        """获取今日需复习的单词"""
        # 如果剩余单词不足，自动重置进度
        if len(self.state["remaining"]) < count:
            self._reset_state(force=True)

        # 随机选择单词
        selected_ids = random.sample(self.state["remaining"], k=min(count, len(self.state["remaining"])))
        
        # 更新状态
        self.state["reviewed"].extend(selected_ids)
        self.state["remaining"] = [i for i in self.state["remaining"] if i not in selected_ids]
        self.state["last_review"] = datetime.now().isoformat()
        self._save_state()

        # 获取单词详情
        cur = self.conn.execute(f"""
            SELECT id, word FROM words
            WHERE id IN ({','.join('?'*len(selected_ids))})
        """, selected_ids)
        
        return cur.fetchall()

    def show_progress(self):
        """显示当前进度"""
        total = len(self.state["remaining"]) + len(self.state["reviewed"])
        return (
            f"📊 学习进度\n"
            f"✅ 已复习: {len(self.state['reviewed'])}/{total}\n"
            f"⏳ 剩余: {len(self.state['remaining'])}\n"
            f"📅 最后复习时间: {self.state['last_review'] or '从未'}"
        )

def main():
    parser = argparse.ArgumentParser(description="每日单词抽样系统")
    parser.add_argument('-n', '--number', type=int, 
                      help="今日要抽取的单词数量（必选）")
    parser.add_argument('-r', '--reset', action='store_true',
                      help="重置学习进度")
    parser.add_argument('-p', '--progress', action='store_true',
                      help="显示当前进度")
    args = parser.parse_args()

    sampler = WordSampler()

    if args.reset:
        if sampler._reset_state():
            print("🔄 学习进度已重置")
        return

    if args.progress:
        print(sampler.show_progress())
        return

    if not args.number:
        print("❌ 请使用 -n 指定要抽取的单词数量")
        return

    try:
        words = sampler.get_daily_words(args.number)
        if not words:
            print("⚠️ 数据库中没有单词，请先添加单词")
            return

        print(f"\n🎯 今日 {len(words)} 个待复习单词：")
        for idx, (word_id, word) in enumerate(words, 1):
            print("\n***")
            print(f"{idx}. [{word_id}] {word}")
            result = api.query(word)
            if isinstance(result, str):
                # 处理错误情况
                print(f"查询失败: {result}")
                continue
    
            # 获取格式化输出
            formatted = api.format_result(data=result, color=True)
            print(formatted)
            print("---")

        print(f"\n{sampler.show_progress()}")
    except ValueError as e:
        print(f"❌ 错误：{str(e)}")

if __name__ == "__main__":
    main()